from langchain.agents import Tool,create_react_agent,AgentExecutor,tool
from langchain_core.prompts import PromptTemplate,ChatPromptTemplate
from langchain_community.llms import Tongyi
import requests  # 假设用于 API 调用
import json
from rbac.models import UserModel,WorkFlowModel

from workflow.models import TaskWorkFlowModel

llm = Tongyi()


# 模拟工具函数
def submit_request(request_data):
    # 这里可以调用实际的 API 来提交请求
    # 例如：requests.post('http://your-api-endpoint', json=request_data)
    data=json.loads(request_data)
    user_id = data['user_id']
    workflow_id = data['workflow_id']
    params = json.dumps(data['params'])
    ea_user_id = data['ea_user_id']
    user_data = UserModel.objects.filter(id=user_id).values('username','department__name').first()
    workflow_name = WorkFlowModel.objects.filter(id=workflow_id).values('name').first()
    task_workflow = TaskWorkFlowModel.objects.create(
        user_id=user_id,
        workflow_id=workflow_id,
        next_audit=ea_user_id,
        task_status=1,
        params=params,
        name=f"{user_data['username']}-{user_data['department__name']}-{workflow_name['name']}",
    )
    return task_workflow.id









def assign_approver(request_id):
    # 根据部门、职位等规则分配审批者
    # 这里可以查询数据库或调用其他服务来获取审批者信息
    request_id = int(request_id)
    task = TaskWorkFlowModel.objects.filter(id=request_id).first()
    username = task.user.username
    workflow_name = task.workflow.name
    params = json.loads(task.params)




    # send_email(approver, f"You have a new approval request with ID {request_id}")
    return 'ok'


def record_decision(request_id):
    data = json.loads(request_id)
    print(data)
    decision = data['decision']
    request_id = data['request_id']
    # 记录审批者的决策
    print(f"Recording decision '{decision}' for request {request_id}")
    # 可以调用 API 或更新数据库
    return f"Decision recorded for request {request_id}: {decision}"


def update_status(request_id):
    data = json.loads(request_id)
    print("***")
    print(data)
    rid = data['request_id']
    status = data['new_status']
    print("******")

    # 更新审批请求的状态
    print(f"Updating status of request {rid} to {status}")
    # 可以调用 API 或更新数据库
    return f"Status updated for request {request_id} to "


# 定义工具
tools = [
    Tool(
        name="SubmitRequest",
        func=submit_request,
        description="当用户输入的工具名为AssignApprover，使用这个工具,并把工具所需要的数据转换成json类型."
    ),
    Tool(
        name="AssignApprover",
        func=assign_approver,
        description="当用户输入的工具名为AssignApprover，使用这个工具,并把用户传来的数据转换成dict类型。Assign an approver for a given request ID. Takes request ID as input."
    ),
    Tool(
        name="RecordDecision",
        func=record_decision,
        description="当用户输入的工具名为RecordDecision，使用这个工具。Record the approver's decision for a request. Takes request ID and decision as input use dict."
    ),
    Tool(
        name="UpdateStatus",
        func=update_status,
        description="当用户输入的工具名为UpdateStatus，使用这个工具。Update the status of a request. Takes request ID and new status as input use dict."
    )
]

template = '''Answer the following questions as best you can. You have access to the following tools:

            {tools}

            Use the following format:
            Question: 根据用户输入的工具名{toolname}来选择工具,最多选择一个工具，把输入的{input}调用工具使用,不要改变{input}的数据类型
            Thought: 根据用户输入的工具名{toolname}来选择工具,最多选择一个工具，把输入的{input}调用工具使用,不要改变{input}的数据类型
            Action: the action to take, should be one of [{tool_names}],最多使用一次工具
            Action Input: the input to the action,根据工具的要求，把输入的{input}转换成工具需要的数据类型,不要改变{input}的数据类型
            Observation: the result of the action
            ... (this Thought/Action/Action Input/Observation can repeat N times)
            Final Answer: 返回使用工具后的结果，不要对结果进行任何处理

            Begin!

            Question: {input}
            Thought:{agent_scratchpad}
            '''

prompt = ChatPromptTemplate.from_template(template)


# 创建agent对象
agent = create_react_agent(llm=llm,tools=tools,prompt=prompt)
# 创建agentexecuter对象
agent_executor = AgentExecutor(agent=agent,tools=tools,verbose=False)

# 示例使用
def main(data):
    # 提交请求
    submit_result = agent_executor.invoke({"input":data,"toolname":"SubmitRequest"})
    request_id = submit_result['output']
    # # 假设请求提交后得到一个 request_id
    # request_id = "12345"
    # # 分配审批者
    assign_result = agent_executor.invoke({"input":request_id,"toolname":"AssignApprover"})
    # print(assign_result)
    # # 审批者决策
    # decision = 1
    # record_result = agent.invoke(f"RecordDecision {request_id} {decision}")
    # print(record_result)
    # # 更新状态
    # status = 1
    # update_result = agent.invoke(f"UpdateStatus {request_id} and status is {status}")
    # print(update_result)


wfagent = main

# if __name__ == "__main__":
#     main()


# class TaskView(APIView):
#     def post(self, request):
#         # 获取参数
#         mes = request.data
#         taskid = audit_workflow("提交任务，数据为:" + json.dumps(mes))
#         audit_workflow("分配审核人，任务id为：" + str(taskid))
#         return Response({"code": 200})
#
#
# class UserAuditView(APIView):
#     def post(self, request):
#         # 获取参数
#         mes = request.data
#         flag = audit_workflow("分配审核人，任务id为：" + str(taskid))
#         if flag == 'success':
#             audit_workflow("更新审核结果,数据为:" + json.dumps(mes))